
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Link } from 'react-router-dom';
import $ from 'jquery';
import {
  Button,
  Spinner
} from 'react-bootstrap';

import { function_register } from '../../actions/passport';

import { URL, CODE } from '../../config';

import { PRODUCT_NAME } from '../../config';

import Input from '../../components/passport/Registerinput';

import './less/register.css';

class App extends Component {

  state = {
    companyName: "",
    companyNameIsError: false,
    companyNameErrorMsg: "",
    userName: "",
    userNameIsError: false,
    userNameErrorMsg: "",
    email: "",
    emailIsError: false,
    emailErrorMsg: "",
    password: "",
    passwordIsError: false,
    passwordErrorMsg: "",
    loadingFlg: false,
  }

  componentDidMount () {
    $("#company-name").focus();
  }

  handleCompanyNameChange (event) {
    this.setState({ companyName: event.target.value })
  }

  handleUserNameChange (event) {
    this.setState({ userName: event.target.value })
  }

  handleEmailChange (event) {
    this.setState({ email: event.target.value })
  }

  handlePasswordChange (event) {
    this.setState({ password: event.target.value })
  }

  handleCompanyNameBlur () {
    let errorMsg = "";

    var regPrex = /^[\u4e00-\u9fa5a-zA-Z]+[\u4e00-\u9fa5a-zA-Z0-9\-_]*$/
    if (!regPrex.test(this.state.companyName)) {
      errorMsg = "公司或组织名称请输入中英文、下划线、英文句号和数字，且只能以中英文开头";
    }

    if (this.state.companyName === "") {
      errorMsg = "公司或组织不能为空";
    }

    if (errorMsg !== "") {
      this.setState({
        companyNameIsError: true,
        companyNameErrorMsg: errorMsg
      });
    } else {
      this.setState({
        companyNameIsError: false,
        companyNameErrorMsg: ""
      });
    }
  }

  handleUserNameBlur () {
    let errorMsg = "";

    if (this.state.userName.length < 2) {
      errorMsg = "昵称长度不能少于2字符";
    }

    let regPrex = /^[\u4e00-\u9fa5a-zA-Z]+[\u4e00-\u9fa5a-zA-Z0-9\-_]*$/
    if (!regPrex.test(this.state.userName)) {
      errorMsg = "昵称请输入中英文、下划线、英文句号和数字，且只能以中英文开头";
    }

    if (this.state.userName === "") {
      errorMsg = "昵称不能为空";
    }

    if (errorMsg !== "") {
      this.setState({
        userNameIsError: true,
        userNameErrorMsg: errorMsg
      });
    } else {
      this.setState({
        userNameIsError: false,
        userNameErrorMsg: ""
      });
    }
  }

  handleEmailBlur () {
    let errorMsg = "";

    let regPrex = /^([a-zA-Z0-9]+[_|.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/;
    if (!regPrex.test(this.state.email)) {
      errorMsg = "邮箱格式不正确";
    }

    if (this.state.email === "") {
      errorMsg = "昵称不能为空";
    }

    if (errorMsg !== "") {
      this.setState({
        emailIsError: true,
        emailErrorMsg: errorMsg
      });
    } else {
      this.setState({
        emailIsError: false,
        emailErrorMsg: ""
      });
    }
  }

  handlePasswordBlur () {

    let passwordIsError = false;

    var regex = new RegExp('^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z_!@#$%^&*`~()-+=]+$)(?![a-z0-9]+$)(?![a-z_!@#$%^&*`~()-+=]+$)(?![0-9_!@#$%^&*`~()-+=]+$)[a-zA-Z0-9_!@#$%^&*`~()-+=]{8,16}$');
    if (!regex.test(this.state.password)) {
      passwordIsError = true
    }

    if (this.state.password === "") {
      passwordIsError = true
    }

    if (passwordIsError) {
      this.setState({
        passwordIsError: passwordIsError,
        passwordErrorMsg: "密码为8-16位, 必须包含大小写字母、数字、符号中至少3种"
      });
    } else {
      this.setState({
        passwordIsError: false,
        passwordErrorMsg: ""
      });
    }
  }

  handleCompanyNameFocus () {
    this.setState({
      companyNameIsError: false,
      companyNameErrorMsg: ""
    });
  }

  handleUserNameFocus () {
    this.setState({
      userNameIsError: false,
      userNameErrorMsg: ""
    });
  }

  handleEmailFocus () {
    this.setState({
      emailIsError: false,
      emailErrorMsg: ""
    });
  }

  handlePasswordFocus () {
    this.setState({
      passwordIsError: false,
      passwordErrorMsg: ""
    });
  }

  //表单提交
  handleSubmit () {
    if (!this.state.companyNameIsError &&
      !this.state.userNameIsError &&
      !this.state.emailIsError &&
      !this.state.passwordIsError) {
      this.setState({
        loadingFlg: true
      });
      function_register(
        this.state.companyName,
        this.state.userName,
        this.state.email,
        this.state.password,
        this.props.dispatch, (result) => {
          if (result.code === CODE.PARAM_ERROR) {
            let obj = result.data;
            for (let key in obj) {
              if (key === "organizeName") {
                this.setState({
                  companyNameErrorMsg: obj[key],
                  companyNameIsError: true,
                  loadingFlg: false
                });
              }
              if (key === "nickName") {
                this.setState({
                  userNameErrorMsg: obj[key],
                  userNameIsError: true,
                  loadingFlg: false
                });
              }
              if (key === "email") {
                this.setState({
                  emailErrorMsg: obj[key],
                  emailIsError: true,
                  loadingFlg: false
                });
              }
              if (key === "password") {
                this.setState({
                  passwordErrorMsg: obj[key],
                  passwordIsError: true,
                  loadingFlg: false
                });
              }
            }
          } else {
            window.localStorage.setItem("_uid", result.data.uid);
            window.localStorage.setItem("_organizeid", result.data.organizeid);
            window.localStorage.setItem("_timestamp", result.data.timestamp);
            window.localStorage.setItem("_token", result.data.token);
            this.props.history.push(URL.main_page);
            this.setState({
              loadingFlg: false
            });
          }
        });
    }
  }

  render () {
    return (
      <div className="root-box">
        <div className="layout-logo layout-logo-for-free-register">
        </div>
        <div className="register-form">
          <h2 className="register-title">{"欢迎注册" + PRODUCT_NAME}</h2>

          <Input
            hasError={this.state.companyNameIsError}
            id="company-name"
            maxLength={26}
            placeholder="公司或组织名称"
            type="text"
            value={this.state.companyName}
            onFocus={this.handleCompanyNameFocus.bind(this)}
            onChange={this.handleCompanyNameChange.bind(this)}
            onBlur={this.handleCompanyNameBlur.bind(this)}
            errorTips={this.state.companyNameErrorMsg}
            normalMsg="公司或组织名称，注册后不可变更" />

          <Input
            hasError={this.state.userNameIsError}
            id="nick"
            maxLength={30}
            placeholder="你的工作昵称"
            type="text"
            value={this.state.userName}
            onFocus={this.handleUserNameFocus.bind(this)}
            onChange={this.handleUserNameChange.bind(this)}
            onBlur={this.handleUserNameBlur.bind(this)}
            errorTips={this.state.userNameErrorMsg}
            normalMsg="将以该昵称创建管理员帐号<br />注册完成后可以邀请更多成员加入" />

          <Input
            hasError={this.state.emailIsError}
            id="email"
            maxLength={50}
            placeholder="你的邮箱"
            type="text"
            value={this.state.email}
            onFocus={this.handleEmailFocus.bind(this)}
            onChange={this.handleEmailChange.bind(this)}
            onBlur={this.handleEmailBlur.bind(this)}
            errorTips={this.state.emailErrorMsg}
            normalMsg="" />

          <Input
            hasError={this.state.passwordIsError}
            id="password"
            maxLength={26}
            placeholder="密码（至少8位, 包含大小写字母、数字、符号中至少3种）"
            type="password"
            value={this.state.password}
            onFocus={this.handlePasswordFocus.bind(this)}
            onChange={this.handlePasswordChange.bind(this)}
            onBlur={this.handlePasswordBlur.bind(this)}
            errorTips={this.state.passwordErrorMsg}
            normalMsg="" />

          <div className="form-btn register-btn" onClick={this.handleSubmit.bind(this)}>
            <Button variant="primary" type="submit" disabled={this.state.loadingFlg ? true : false} block>
              {this.state.loadingFlg ?
                <Spinner
                  as="span"
                  animation="border"
                  size="sm"
                  role="status"
                  aria-hidden="true"
                />
                : null}
              注册
            </Button>
          </div>
        </div>
        <div className="show-login-tip show-login-tip-for-register-free-as-email">
          已有帐号，<Link to={URL.login_page}>直接登录</Link>
        </div>
      </div>
    );
  }
}

function mapStateToProps (state) {
  return {}
}

export default connect(mapStateToProps)(App);
